<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/28 0028
 * Time: 下午 6:47
 */
namespace app\api\controller;


use app\admin\model\Storesettlement;
use app\admin\model\Userbuyticket;
use app\admin\model\Usersettlement;
use app\api\service\ShanghuPay;
use app\common\Helper;
use app\common\model\Storesettlerule;
use app\common\model\Userstore;
use app\common\validate\Currency;
use app\common\validate\MakeMoney;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 分销相关接口
 * Class Distribution
 * @package app\api\controller
 */
class Distribution extends Base{

    //获取一级分销用户
    public function getDistributeMemberF(Request $request){
        $param = $request->param();
        $start = $param['start'];
        $length = $param['length'];
        if(!empty($param['keywords'])){
            $keywords = $param['keywords'];
            $fMember = \app\admin\model\Member::where('boss',$param['userId'])->where('name','like','%'.$keywords.'%')->limit($start,$length)->select();
            $count = \app\admin\model\Member::where('boss',$param['userId'])->where('name','like','%'.$keywords.'%')->count();
        }else{
            $fMember = \app\admin\model\Member::where('boss',$param['userId'])->limit($start,$length)->select();
            $count = \app\admin\model\Member::where('boss',$param['userId'])->count();
        }

        $data['member'] = [];
        if($fMember){
            foreach ($fMember as &$v){
                $User = \app\common\model\User::get($v['id']);
                $v['user'] = $User;
                $memAllDis = 0;
                $Distribution = \app\common\model\Distribution::where('memberId',$v['id'])->where('money','>',0)->select();
                if($Distribution){
                    foreach ($Distribution as $value){
                        $memAllDis += (int)$value['money'];
                    }
                }
                $v['memAllDis'] = $memAllDis;
                $sMember = \app\admin\model\Member::where('boss',$v['id'])->count();
                if($sMember>0){
                    $v['isxiaji'] = 1;
                }else{
                    $v['isxiaji'] = 0;
                }
            }

            $data['bossId'] = $param['userId'];
            $data['member'] = $fMember;
            $data['size'] = $count;

            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            return show(2,'暂无一级好友',null);
        }
    }

    public function buyTicketRecord(Request $request){
        $param = $request->param();
        $start = $param['start'];
        $length = $param['length'];
        if(empty($param['distributionUserId']) || empty($param['bossId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }

        $Distribution = \app\common\model\Distribution::where(['memberId'=>$param['distributionUserId'],'bossId'=>$param['bossId']])->where('money','>',0)->limit($start,$length)->select();
        $count = \app\common\model\Distribution::where(['memberId'=>$param['distributionUserId'],'bossId'=>$param['bossId']])->where('money','>',0)->count();
        $data = [];
        if(!empty($Distribution)){
            $data['size'] = $count;
            foreach ($Distribution as &$v){
                $User = \app\common\model\User::get($v['memberId']);
                $v['user'] = $User;
                $Userbuyticket = Userbuyticket::where('orderNo',$v['orderNo'])->find();
                $Ticket = \app\admin\model\Ticket::get($v['ticketId']);
                $v['ticket'] = $Ticket;
                $v['buyTicketMoney'] = $Userbuyticket['money'];
                $v['storeName'] = $Userbuyticket['storeName'];
            }
            $data['userBuyTickets'] = $Distribution;

            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }


    }

    public function subordinateDetails(Request $request){
        $param = $request->param();
        if(empty($param['bossId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $start = $param['start'];
        $length = $param['length'];

        $Member = \app\admin\model\Member::where('boss',$param['bossId'])->limit($start,$length)->select();
        $count = \app\admin\model\Member::where('boss',$param['bossId'])->count();
        $data['member'] = [];
        if($Member){
            foreach ($Member as &$v){
                $User = \app\common\model\User::get($v['id']);
                $v['user'] = $User;
                $memAllDis = 0;
                $Distribution = \app\common\model\Distribution::where('memberId',$v['id'])->where('money','>',0)->select();
                if($Distribution){
                    foreach ($Distribution as $value){
                        $memAllDis += (int)$value['money'];
                    }
                }
                $v['memAllDis'] = $memAllDis;
            }

            $data['member'] = $Member;
            $data['size'] = $count;
            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            return show(2,'暂无二级好友',null);
        }



    }

    /**
     * 提现申请
     */
    public function PutforwardApply(Request $request){
        try{
            (new Currency())->goCheck();
        }catch(Exception $ex){
            return show(config('status.ERROR_STATUS'),'提现金额不合法','提现金额不合法');
        }
        $param = $request->param();
        if(empty($param['userId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        Db::startTrans();
        try{
            if($param['targetType'] == 1){
                $Member = \app\admin\model\Member::get($param['userId']);
                if(!$Member){
                    throw new ParameterException([
                        'msg' => '用户不合法'
                    ]);
                }
                $count = Usersettlement::where('userId',$param['userId'])->whereTime('createDate','today')->count();
                $Storesettlerule = Storesettlerule::where(true)->find();
                if($Storesettlerule->settleTime <= $count){
                    throw new ParameterException([
                        'msg' => '今天提现次数已经用完了！'
                    ]);
                }
                if($param['amount'] > $Member->distributeComm){
                    throw new ParameterException([
                        'msg' => '提现金额超过余额'
                    ]);
                }
                $amount = $param['amount'];
                $Usersettlement = new Usersettlement();
                $Usersettlement->id = Helper::getUUID();
                $Usersettlement->userId = $Member->id;
                $Usersettlement->withdrawalAccount = 1;
                $Usersettlement->amount = $amount;
                $Usersettlement->orderNo = \app\api\service\Pay::makeOrderNo();
                if($Usersettlement->save()){
                    $Member->setDec('distributeComm',$amount);
                }else{
                    throw new ParameterException([
                        'msg' => '提现申请失败，内部原因'
                    ]);
                }
            }else{
                //店铺提现
                $Userstore = Userstore::where('userId',$param['userId'])->find();
                if(!$Userstore){
                    throw new ParameterException([
                        'msg' => '用户店铺异常'
                    ]);
                }
                $Store = \app\admin\model\Store::get($Userstore->storeId);
                if(!$Store || $Store->status != 1){
                    throw new ParameterException([
                        'msg' => '店铺不存在'
                    ]);
                }
                if($param['amount'] > $Store->balance){
                    throw new ParameterException([
                        'msg' => '提现金额超过余额'
                    ]);
                }
                $amount = $param['amount'];
                $Storesettlement = new Storesettlement();
                $Storesettlement->id = Helper::getUUID();
                $Storesettlement->amount = $amount;
                $Storesettlement->withdrawalAccount = 1;
                $Storesettlement->orderNo = \app\api\service\Pay::makeOrderNo();
                $Storesettlement->storeId = $Store->id;
                if($Storesettlement->save()){
                    $Store->setDec('balance',$amount);
                }else{
                    throw new ParameterException([
                        'msg' => '提现申请失败，内部原因'
                    ]);
                }
            }
            Db::commit();
            return show(config('status.SUCCESS_STATUS'),'创建提现申请订单成功',$Usersettlement);
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),isset($ex->msg)?$ex->msg:$ex->getMessage(),'提现失败');
        }





    }

    public function MakeMoney(Request $request){
        (new MakeMoney())->goCheck();
        $param = $request->param();
        $dpay = new ShanghuPay($param['id'],$param['userId']);
        return $dpay->shanghuPay($param['targetType']);
    }


    public function putforwardRecord(Request $request){
        $param = $request->param();
        $start = $param['start'];
        $length = 10;
        $Usersettlement = Usersettlement::where('userId',$param['userId'])->order('createDate DESC')->limit($start,$length)->select();
        $count = Usersettlement::where('userId',$param['userId'])->count();

        if($Usersettlement){
            $data['size'] = $count;
            $data['data'] = $Usersettlement;

            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            show(2,'暂无记录',null);
        }
    }

    public function putforwardrule(Request $request){
        $param = $request->param();
        $Storesettlerule = Storesettlerule::where(true)->find();
        if($Storesettlerule){
            $count = Usersettlement::where('userId',$param['userId'])->whereTime('createDate','today')->count();
            $shenyucount = $Storesettlerule->settleTime - $count;
            $Storesettlerule['shengyucount'] = $shenyucount;
            return show(config('status.SUCCESS_STATUS'),'ok',$Storesettlerule);
        }else{
            return show(2,'暂无数据',null);
        }
    }


}